package xyz.jfshare.netty.study.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xyz.jfshare.netty.study.server.dao.MessageMapper;
import xyz.jfshare.netty.study.server.entity.Message;
import xyz.jfshare.netty.study.server.service.MessageService;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {
    @Autowired
    private MessageMapper messageMapper;

    @Override
    public List<Message> getSystemMsgByUserId(int id) {
        return list(
                new QueryWrapper<Message>()
                        .eq("is_delete",0)
                        .eq("is_read",0)
                        .eq("to_id",id)
                        .eq("type",2)
        );
    }

    @Override
    public  List<Message> getUserMsgByUserId(int id) {
        return list(
                new QueryWrapper<Message>()
                        .eq("is_delete",0)
                        .eq("to_id",id)
                        .eq("type",1)
                        .orderByAsc("id")
        );
    }

    @Override
    public Message getById(int id) {
        return getOne(
                new QueryWrapper<Message>().eq("is_delete",0).eq("id",id)
        );
    }

    @Override
    public int insert(Message message) {
        return messageMapper.insert(message);
    }

    @Override
    public List<Message> getChatRecord(int fromId, int toId) {
        List<Message> fromMsg = getUserMsgByUserId(fromId);
        List<Message> toMsg = getUserMsgByUserId(toId);
        List<Message> list = new ArrayList<>();
        int i = 0,j = 0;
        while (i < fromMsg.size() && j < toMsg.size()){
            if (fromMsg.get(i).getId() < toMsg.get(j).getId()){
                list.add(fromMsg.get(i));
                i++;
            }else {
                list.add(toMsg.get(j));
                j++;
            }
        }
        return list;
    }
}
